package com.cl.security.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

public class FileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    public static void get(String fileName, HttpServletResponse response) {
        try {
          byte[] bytes = cn.hutool.core.io.FileUtil.readBytes(new File(ConfigUtil.getFilePath() + fileName));
          response.getOutputStream().write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String upload(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            assert filename != null;
            String[] fileNames = filename.split("\\.");
            String suffix = fileNames[fileNames.length - 1];
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName =  System.currentTimeMillis() + "." +suffix;
            file.transferTo(new File(ConfigUtil.getFilePath() + fileName));
            LOGGER.info("文件上传成功!");
            return fileName;
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {}！", e.getMessage());
            return null;
        }
    }

    public static boolean delete(@RequestParam("fileName") String fileName) {
        try {
//            MinioClient minioClient = new MinioClient(ConfigUtil.getEndpoint(), ConfigUtil.getAccessKey(), ConfigUtil.getSecretKey());
//            minioClient.removeObject(ConfigUtil.getBucketName(), fileName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
